// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID

  try {
    // 从事件中获取更新数据
    const {
      nickName,
      realName,
      avatarUrl,
      phoneNumber,
      gender,
      birthday,
      region,
      detail,
      updatedAt
    } = event

    // 验证必填字段
    if (!nickName || nickName.trim().length === 0) {
      return {
        success: false,
        message: '昵称不能为空'
      }
    }

    // 构建更新数据
    const updateData = {
      nickName: nickName.trim(),
      updatedAt: updatedAt || new Date()
    }

    // 添加可选字段
    if (realName !== undefined) {
      updateData.realName = realName.trim()
    }
    
    if (avatarUrl !== undefined) {
      updateData.avatarUrl = avatarUrl
    }
    
    if (phoneNumber !== undefined) {
      updateData.phoneNumber = phoneNumber.trim()
    }
    
    if (gender !== undefined) {
      updateData.gender = parseInt(gender) || 0
    }
    
    if (birthday !== undefined) {
      updateData.birthday = birthday
    }
    
    if (region !== undefined && Array.isArray(region)) {
      updateData.region = region
    }
    
    if (detail !== undefined) {
      updateData.detail = detail.trim()
    }

    // 查询用户是否存在
    const userQuery = await db.collection('users').where({
      _openid: openid
    }).get()

    if (userQuery.data.length === 0) {
      return {
        success: false,
        message: '用户不存在'
      }
    }

    const user = userQuery.data[0]

    // 更新用户信息
    const updateResult = await db.collection('users').doc(user._id).update({
      data: updateData
    })

    if (updateResult.stats.updated === 1) {
      // 获取更新后的用户信息
      const updatedUserQuery = await db.collection('users').where({
        _openid: openid
      }).get()

      const updatedUser = updatedUserQuery.data[0]

      // 获取会员等级信息
      if (updatedUser.memberLevel) {
        const memberLevelQuery = await db.collection('member_levels').where({
          level: updatedUser.memberLevel
        }).get()

        if (memberLevelQuery.data.length > 0) {
          updatedUser.memberLevelInfo = memberLevelQuery.data[0]
        }
      }

      return {
        success: true,
        message: '更新成功',
        data: updatedUser
      }
    } else {
      return {
        success: false,
        message: '更新失败'
      }
    }

  } catch (error) {
    console.error('更新用户资料失败:', error)
    return {
      success: false,
      message: error.message || '更新失败',
      error: error
    }
  }
}